unit uFrmSellTicket;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, dateutils,
  Dialogs, ExtCtrls, StdCtrls, umainutils, DBCtrls, uprintticket, uFrmCameraGetImage, strutils, OracleData, uutils, math, DB, uFrmInsertNewplayer, gnugettext, uSQLs, EditPlayers;

type
  Tfrm_SellTicket = class(TForm)
    DataSource1: TDataSource;
    OracleDataSet1: TOracleDataSet;
    Panel1: TPanel;
    pnl_EditPlayer: TPanel;
    pnl_SubjectImage: TPanel;
    Label13: TLabel;
    img_Player: TImage;
    btn_ChangePicture: TButton;
    btn_PhotoFromWebCam: TButton;
    GroupBox1: TGroupBox;
    lbl_TicketSold: TLabel;
    Label9: TLabel;
    Panel2: TPanel;
    Label5: TLabel;
    Panel3: TPanel;
    btn_Cancel: TButton;
    btn_Ok: TButton;
    pnl_TicketType: TLabel;
    lbl_TournamentName: TLabel;
    pnl_CalcTicket: TPanel;
    lbl_Fee: TLabel;
    Label1: TLabel;
    Label4: TLabel;
    lbl_TotalCash: TLabel;
    lbl_Currency1: TLabel;
    lbl_Currency2: TLabel;
    edt_BuyIn: TEdit;
    edt_Fee: TEdit;
    com_FeeType: TComboBox;
    pnl_SeatTablePos: TPanel;
    Label6: TLabel;
    Label7: TLabel;
    com_Table: TComboBox;
    com_Seat: TComboBox;
    btn_RandomPosition: TButton;
    btn_ClearEdit: TButton;
    com_Player: TDBLookupListBox;
    btn_SavePlayerData: TButton;
    procedure com_TableChange(Sender: TObject);
    procedure btn_CancelClick(Sender: TObject);
    procedure btn_RandomPositionClick(Sender: TObject);
    procedure edt_BuyInChange(Sender: TObject);
    procedure btn_OkClick(Sender: TObject);
    procedure com_Player2Click(Sender: TObject);
    procedure FormKeyPress(Sender: TObject; var Key: Char);
    procedure FormCreate(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure btn_ChangePictureClick(Sender: TObject);
    procedure btn_PhotoFromWebCamClick(Sender: TObject);
    procedure com_Player2CloseUp(Sender: TObject);
    procedure btn_ClearEditClick(Sender: TObject);
    procedure com_RakeTypeChange(Sender: TObject);
    procedure com_FeeTypeChange(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure btn_SavePlayerDataClick(Sender: TObject);
  private
    { Private declarations }
    m_TournamentID, m_LateRegMinutes, m_CashGameID, m_TicketID, m_DoRebuyId, m_DoAddonId: string;
    m_EventStart: TDateTime;
    m_RebuyAllowed, m_AddonAllowed, isNameFocused, m_isCashGame: boolean;
    uEditPlayers: TuFrmEditPlayers;
    procedure PopulateTableCombo(TournamentID: string);
    procedure PopulateSeatCombo(TournamentID: string);
    procedure CalcTotalCash();
    function GetTournamentData(TournamentID: string): boolean;
    procedure GetCashGameData(CashGameID, DoRebuyID: string);
    procedure GetPlayerTicketData(PlayerID, DoRebuyID, DoAddonID: string);
    procedure PopulateCashGameTableAndSeat(CashGameID: string);
    procedure ShowFeeComponents(ShowIt: boolean);
    procedure GetTableAndSeat(TournamentID, CashGameID, TicketId, PlayerID: string);
  public
    { Public declarations }
    M_dATEtIMEvALUE: TDateTime;
    m_TicketType, m_Fee, m_BuyIn: STRING;
    m_MinBuyIn: double;
    function PopulatePlayerCombo(Name, Surname: string; Sender: TObject): boolean;
    procedure ShowSellTicketForm(BuyValue, TournamentID, PlayerID, TicketId: string; CashGameID: string = ''; DoRebuyID: string = ''; DoAddonID: string = '');
  end;

var
  frm_SellTicket: Tfrm_SellTicket;

implementation

uses uFrmMain, ufrmCageTournament, ufrmCageCashGame;
{$R *.dfm}
{ Tfrm_SellTicket }

procedure Tfrm_SellTicket.btn_CancelClick(Sender: TObject);
begin
  close();
end;

procedure Tfrm_SellTicket.btn_ChangePictureClick(Sender: TObject);
var
  FileExt: string;
begin
  if com_Player.KeyValue = null then
  begin
    ShowMessage(_('First select player!'));
  end
  else
  begin
    FrmMain.OpenPictureDialog1.Execute();
    FileExt := ReplaceStr(UpperCase(ExtractFileExt(FrmMain.OpenPictureDialog1.FileName)), '.', '');
    if FrmMain.OpenPictureDialog1.FileName <> '' then
    begin
      FrmMain.SavePhotoToDB(FrmMain.OpenPictureDialog1.FileName, FileExt, com_Player.KeyValue);
    end;
  end;
end;

procedure Tfrm_SellTicket.btn_ClearEditClick(Sender: TObject);
begin
  uEditPlayers.ClearBoxes;
  edt_BuyIn.Text := '';
  edt_Fee.Text := '';
  lbl_TicketSold.Caption := '';
  com_Player.KeyValue := null;
  img_Player.Picture := nil;
  PopulatePlayerCombo('', '', nil);
  isNameFocused := true;
  m_TicketType := '';
  pnl_TicketType.Caption := '';
  com_Table.Text := '';
  com_Seat.Text := '';
  btn_RandomPosition.Enabled := true;
  com_Player.Visible := false;
  CalcTotalCash();
end;

procedure Tfrm_SellTicket.btn_OkClick(Sender: TObject);
var
  SQLvalues, SeatNum, TableNum, TableID, PlayerID: string;
begin
  SeatNum := com_Seat.Text;
  TableNum := com_Table.Text;
  if (edt_BuyIn.Text = '') then
  begin
    ShowMessage(_('Buy in must be at least' + ' ' + FloatToStr(m_MinBuyIn) + ' ' + Currency_Symbol));
    exit;
  end;
  if (m_MinBuyIn > StrToFloat(edt_BuyIn.Text)) then
  begin
    ShowMessage(_('Buy in must be at least' + ' ' + FloatToStr(m_MinBuyIn) + ' ' + Currency_Symbol));
    exit;
  end;
  TableID := '';
  if TableNum <> '' then
  begin
    FrmMain.OracleQuery1.SQL.Clear;
    FrmMain.OracleQuery1.SQL.Text := ('select * from TABLES WHERE NAME=''' + TableNum + '''');
    FrmMain.OracleQuery1.Execute;
    TableID := (FrmMain.OracleQuery1.Field('ID'));
  end;
  if com_Player.KeyValue = null then
  begin
    uEditPlayers.btn_Save.Click();
    PlayerID := uEditPlayers.NewRecordId;
  end
  else
  begin
    PlayerID := inttostr(com_Player.KeyValue);
  end;
  { if m_TicketType = TicketTypeRebuy then
    begin
    FrmMain.OracleQuery1.SQL.Clear;
    FrmMain.OracleQuery1.SQL.Text := ('select table_id, seat_num from tickets where id=''' + m_TicketID + '''');
    FrmMain.OracleQuery1.Execute;
    TableID := (FrmMain.OracleQuery1.Field('table_id'));
    SeatNum := (FrmMain.OracleQuery1.Field('seat_num'));
    end; }
  if m_isCashGame then
  begin
    if m_TicketType = TicketTypeBuy then
    begin
      if ((SeatNum = '') or (TableNum = '')) and pnl_SeatTablePos.Visible then
      begin
        ShowMessage(_('Select Table and Seat!'));
        exit;
      end;
      SQLvalues := '(SELECT * FROM GET_GD_START_TIME)' + ',' + PlayerID + ', ' + '''' + m_CashGameID + '''' + ', ' + '''' + TableID + '''' + ', ' + '''' + SeatNum + '''' + ', ' + '0' + ', ' + '''' +
        edt_BuyIn.Text + '''' + ', ' + 'to_date(''' + GetFormatedStringDateNOW(FrmMain.OracleSession1) + ''', ''dd.mm.yyyy hh24:mi:ss'')';
      m_TicketID := InsertDataIntoDB('CASH_GAME_TICKETS', 'GAMING_DAY, PLAYER_ID, CASH_GAME_ID, TABLE_ID, SEAT_NUM, DELETED, INPUT_VALUE, DATETIME', SQLvalues);
    end
    else if m_TicketType = TicketTypeRebuy then
    begin
      if m_DoRebuyId = '' then
      begin
        InsertRebuyOrAddon(m_isCashGame, true, false, m_TicketID, edt_BuyIn.Text, m_CashGameID);
      end
      else
      begin
        FrmMain.UpdateRebuyOrAddon(m_isCashGame, true, m_DoRebuyId, edt_BuyIn.Text);
        m_TicketID := m_DoRebuyId;
      end;
    end;
    FrmMain.SendEventToServer(EventTypeTicket, m_CashGameID, '');
  end
  else
  begin
    if m_TicketType = TicketTypeBuy then
    begin
      if ((SeatNum = '') or (TableNum = '')) and pnl_SeatTablePos.Visible then
      begin
        ShowMessage(_('Select Table and Seat!'));
        exit;
      end;
      SQLvalues := PlayerID + ', ' + '''' + m_TournamentID + '''' + ', ' + '''' + edt_Fee.Text + '''' + ', ' + '''' + '' + '''' + ', ' + '''' + TableID + '''' + ', ' + '''' + SeatNum + '''' + ', ' +
        '0' + ', ' + '0' + ', ' + '''' + edt_BuyIn.Text + '''' + ', ' + 'to_date(''' + GetFormatedStringDateNOW(FrmMain.OracleSession1) + ''', ''dd.mm.yyyy hh24:mi:ss'')';
      m_TicketID := InsertDataIntoDB('TICKETS', 'PLAYER_ID, TOURNAMENT_ID, FEE, RAKE, TABLE_ID, SEAT_NUM, TICKET_CODE, DELETED, BUY_IN, DATETIME', SQLvalues);
    end
    else if m_TicketType = TicketTypeRebuy then
    begin
      if m_DoRebuyId = '' then
      begin
        InsertRebuyOrAddon(m_isCashGame, true, false, m_TicketID, edt_BuyIn.Text, m_TournamentID);
      end
      else
      begin
        FrmMain.UpdateRebuyOrAddon(m_isCashGame, true, m_DoRebuyId, edt_BuyIn.Text);
      end;
    end
    else if m_TicketType = TicketTypeAddon then
    begin
      if m_DoAddonId = '' then
      begin
        InsertRebuyOrAddon(m_isCashGame, false, false, m_TicketID, edt_BuyIn.Text, m_TournamentID);
      end
      else
      begin
        FrmMain.UpdateRebuyOrAddon(m_isCashGame, false, m_DoAddonId, edt_BuyIn.Text);
      end;
    end;
    FrmMain.SendEventToServer(EventTypeTicket, m_TournamentID, TableID);
  end;
  close();
  FrmPrintTicket.SetData(m_isCashGame, m_TicketID, m_TicketType, FrmMain.OracleSession1);
end;

procedure Tfrm_SellTicket.btn_PhotoFromWebCamClick(Sender: TObject);
begin
  if com_Player.KeyValue = null then
  begin
    ShowMessage(_('First Save new player or Select player!'));
  end
  else
  begin
    FrmMain.ShowCAMphotoForm(com_Player.KeyValue);
    if (FrmCameraGetImage.FrmSubjectImage.img_TakenPhoto.Picture <> nil) and (FrmCameraGetImage.ImageValid) then
      img_Player.Picture := FrmCameraGetImage.FrmSubjectImage.img_TakenPhoto.Picture;
  end;
end;

procedure Tfrm_SellTicket.btn_RandomPositionClick(Sender: TObject);
begin
  if not m_isCashGame then
  begin
    FrmMain.OracleQuery1.SQL.Clear;
    FrmMain.OracleQuery1.SQL.Text := ('select id,name from(select t.id, (t.seats-count(ti.id)) as seats_free, t.name  from TOURNAMENT_TABLES tt left join tables t on tt.TABLE_ID = t.ID' +
        ' left join (select * from tickets where TOURNAMENT_ID=' + m_TournamentID + ' and deleted=0) ti on ti.TABLE_ID=t.ID where tt.TOURNAMENT_ID = ' + m_TournamentID +
        ' group by t.seats,t.name, t.id, t.seats' + ' order by seats_free desc) where rownum=1');
    FrmMain.OracleQuery1.Execute;
    if not FrmMain.OracleQuery1.eof then
    begin
      com_Table.Text := FrmMain.OracleQuery1.Field('NAME');
    end
    else
    begin
      ShowMessage(_('Set tournament tables!'));
    end;
  end
  else
  begin
    com_Table.ItemIndex := 0;
  end;
  com_TableChange(NIL);
  com_Seat.ItemIndex := RandomRange(0, com_Seat.Items.Count);
  btn_RandomPosition.Enabled := false;
end;

procedure Tfrm_SellTicket.btn_SavePlayerDataClick(Sender: TObject);
begin
  uEditPlayers.btn_Save.Click;
end;

procedure Tfrm_SellTicket.ShowFeeComponents(ShowIt: boolean);
begin
  com_FeeType.Visible := ShowIt;
  edt_Fee.Visible := ShowIt;
  lbl_Fee.Visible := ShowIt;
end;

procedure Tfrm_SellTicket.CalcTotalCash;
var
  BuyIn, Fee: double;
begin
  if edt_BuyIn.Text <> '' then
    BuyIn := StrToFloat(edt_BuyIn.Text)
  else
    BuyIn := 0;
  // -----
  if edt_Fee.Text <> '' then
    Fee := StrToFloat(edt_Fee.Text)
  else
    Fee := 0;
  if com_FeeType.Text = '%' then
  begin
    Fee := BuyIn / 100 * Fee;
  end;
  // -----
  lbl_TotalCash.Caption := FloatToStr(BuyIn + Fee);
end;

procedure Tfrm_SellTicket.com_FeeTypeChange(Sender: TObject);
begin
  CalcTotalCash();
end;

procedure Tfrm_SellTicket.GetPlayerTicketData(PlayerID, DoRebuyID, DoAddonID: string);
var
  LateRegistrationTime: TDateTime;
begin
  if PlayerID <> '-1' then
  begin
    img_Player.Picture := uutils.GetImage(SQL_Player_Picture + PlayerID, FrmMain.OracleSession1, true);
    FrmMain.OracleQuery1.SQL.Clear;
    FrmMain.OracleQuery1.SQL.Text := ('select count(TI.player_id), birth_date, country_ID from players pl left join (select count(1), player_id from tickets ti where deleted=0 and player_id=' +
        PlayerID + ' group by player_id) ti on pl.id=ti.player_id where pl.id=' + PlayerID + ' group by birth_date, country_ID');
    FrmMain.OracleQuery1.Execute;
    if not FrmMain.OracleQuery1.eof then
    begin
      lbl_TicketSold.Caption := FrmMain.OracleQuery1.Field(0);
    end
    else
    begin
      lbl_TicketSold.Caption := '';
    end;
    uEditPlayers.ShowForm(true, false, PlayerID, true);
  end;
  // GET TICKET TYPE
  pnl_TicketType.Caption := '';
  if PlayerID <> '-1' then
  begin
    if DoRebuyID <> '' then
    begin
      m_TicketType := TicketTypeRebuy;
    end
    else if DoAddonID <> '' then
    begin
      m_TicketType := TicketTypeAddon;
    end
    else
    begin
      FrmMain.OracleQuery1.close;
      FrmMain.OracleQuery1.SQL.Clear;
      FrmMain.OracleQuery1.SQL.Text := (
        'SELECT REBUY_OR_ADDON, TI.ID AS TICKET_ID FROM TICKETS TI LEFT JOIN GETPRESENTTOURNAMENTROUNDDATA GPP ON GPP.TOURNAMENT_ID=TI.TOURNAMENT_ID WHERE TI.DELETED=0 AND TI.TOURNAMENT_ID=' +
          m_TournamentID + ' AND TI.PLAYER_ID=' + PlayerID);
      FrmMain.OracleQuery1.Execute;
      if not FrmMain.OracleQuery1.eof then
      begin
        m_TicketType := FrmMain.OracleQuery1.Field('REBUY_OR_ADDON');
        m_TicketID := FrmMain.OracleQuery1.Field('TICKET_ID');
      end
      else
      begin
        m_TicketType := TicketTypeBuy;
      end;
    end;
    // SET TICKET DATA
    edt_BuyIn.Text := m_BuyIn;
    edt_Fee.Text := m_Fee;
    if m_TicketType = TicketTypeBuy then
    begin
      com_Player.Visible := true;
      // check for late registrations time
      if m_LateRegMinutes = '' then
        m_LateRegMinutes := '0';
      LateRegistrationTime := IncMinute(m_EventStart, strtoint(m_LateRegMinutes));
      if (LateRegistrationTime < now()) then
      begin
        pnl_TicketType.Caption := _('Buy not possible. Late registration time is ended.');
        pnl_SeatTablePos.Visible := false;
        pnl_CalcTicket.Visible := false;
        btn_Ok.Enabled := false;
        exit;
      end;
      // ----
      pnl_TicketType.Caption := m_TicketType + ' ' + _('TICKET');
      pnl_SeatTablePos.Visible := true;
      pnl_CalcTicket.Visible := true;
      ShowFeeComponents(true);
    end
    else if (m_TicketType = TicketTypeRebuy) or (m_TicketType = TicketTypeAddon) then
    begin
      if m_TicketType = TicketTypeAddon then
      begin
        // check how much addons have
        FrmMain.OracleQuery1.close;
        FrmMain.OracleQuery1.SQL.Clear;
        FrmMain.OracleQuery1.SQL.Text := 'SELECT ID FROM TICKET_ADDON WHERE VALUE IS NOT NULL AND TICKET_ID=' + m_TicketID + ' AND TOURNAMENT_ID=' + m_TournamentID;
        FrmMain.OracleQuery1.Execute;
        if not FrmMain.OracleQuery1.eof then
        begin
          com_Player.Visible := true;
          pnl_TicketType.Caption := _('Already ADDON done.');
          btn_Ok.Enabled := false;
          pnl_SeatTablePos.Visible := false;
          pnl_CalcTicket.Visible := false;
          exit;
        end;
      end;
      com_Player.Visible := false;
      pnl_TicketType.Caption := m_TicketType + ' ' + _('TICKET');
      if (m_DoRebuyId <> '') or (m_DoAddonId <> '') then
      begin
        pnl_TicketType.Caption := pnl_TicketType.Caption + #13#10 + _('at table');
      end;
      pnl_SeatTablePos.Visible := true;
      com_Table.Enabled := false;
      com_Seat.Enabled := false;
      pnl_CalcTicket.Visible := true;
      edt_Fee.Text := '0';
      ShowFeeComponents(false);
    end;
    // PLAYER INFO
    if (not m_RebuyAllowed and ((DoRebuyID = '') and (DoAddonID = ''))) and ((m_TicketType = TicketTypeRebuy) or (m_TicketType = '')) then
    begin
      com_Player.Visible := true;
      pnl_TicketType.Caption := _('Already have Ticket. Rebuys not allowed or finished.');
      btn_Ok.Enabled := false;
      pnl_CalcTicket.Visible := false;
      pnl_SeatTablePos.Visible := false;
    end;
  end;
end;

procedure Tfrm_SellTicket.com_Player2Click(Sender: TObject);
var
  PlayerID: string;
begin
  uEditPlayers.IsTypingInEdit := false;
  btn_Ok.Enabled := true;
  PlayerID := VarToStr(com_Player.KeyValue);
  if PlayerID = '' then
    PlayerID := '-1';
  if m_isCashGame then
  begin
    // check if player is already on table
    pnl_CalcTicket.Visible := true;
    if m_TicketType = TicketTypeBuy then
    begin
      FrmMain.OracleQuery1.close;
      FrmMain.OracleQuery1.SQL.Clear;
      FrmMain.OracleQuery1.SQL.Text := 'SELECT * FROM CASH_GAME_TICKETS WHERE CASH_GAME_ID=' + m_CashGameID + ' AND DELETED=0 AND OUT_DATETIME IS NULL AND PLAYER_ID=' + PlayerID;
      FrmMain.OracleQuery1.Execute;
      if not FrmMain.OracleQuery1.eof then
      begin
        com_Player.Visible := false;
        pnl_TicketType.Caption := _('Player already on table!');
        pnl_CalcTicket.Visible := false;
        btn_Ok.Enabled := false;
        exit;
      end;
    end;
    uEditPlayers.ShowForm(true, false, PlayerID, true);
    img_Player.Picture := uutils.GetImage(SQL_Player_Picture + PlayerID, FrmMain.OracleSession1, true);
  end
  else
  begin
    GetPlayerTicketData(PlayerID, m_DoRebuyId, m_DoAddonId);
  end;
  com_Player.Visible := false;
end;

procedure Tfrm_SellTicket.com_Player2CloseUp(Sender: TObject);
begin
  if uEditPlayers.edt_Name.Visible or uEditPlayers.edt_Surname.Visible then
  begin
    if isNameFocused then
    begin
      uEditPlayers.edt_Name.SetFocus;
      uEditPlayers.edt_Name.SelStart := (Length(uEditPlayers.edt_Name.Text));
    end
    else
    begin
      uEditPlayers.edt_Surname.SetFocus;
      uEditPlayers.edt_Surname.SelStart := (Length(uEditPlayers.edt_Surname.Text));
    end;
  end;
end;

procedure Tfrm_SellTicket.com_RakeTypeChange(Sender: TObject);
begin
  CalcTotalCash();
end;

procedure Tfrm_SellTicket.com_TableChange(Sender: TObject);
begin
  if not m_isCashGame then
    PopulateSeatCombo(m_TournamentID);
end;

procedure Tfrm_SellTicket.edt_BuyInChange(Sender: TObject);
begin
  CalcTotalCash();
end;

procedure Tfrm_SellTicket.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  // com_Player.CloseUp(false);
end;

procedure Tfrm_SellTicket.FormCreate(Sender: TObject);
begin
  gnugettext.TranslateComponent(self);
  uEditPlayers := TuFrmEditPlayers.Create(self);
  uEditPlayers.BorderStyle := bsNone;
  uEditPlayers.Align := alclient;
  uEditPlayers.Parent := pnl_EditPlayer;
  uEditPlayers.pnl_Buttons.Visible := false;
  uEditPlayers.Show;
  lbl_Currency1.Caption := Currency_Symbol;
  lbl_Currency2.Caption := Currency_Symbol;
  com_FeeType.Items.Clear;
  com_FeeType.Items.Add(Currency_Symbol);
  com_FeeType.Items.Add('%');
  com_FeeType.Items.Add('');
  com_FeeType.ItemIndex := 2;
end;

procedure Tfrm_SellTicket.FormKeyPress(Sender: TObject; var Key: Char);
begin
  // The Escape key is #27.
  if Key = #27 then
    close;
end;

procedure Tfrm_SellTicket.FormShow(Sender: TObject);
begin
  uEditPlayers.edt_Name.SetFocus();
end;

procedure Tfrm_SellTicket.PopulateCashGameTableAndSeat(CashGameID: string);
var
  I, SeatNum, Seats, SeatIndex: integer;
begin
  // table
  com_Table.Items.Clear;
  FrmMain.OracleQuery1.SQL.Clear;
  FrmMain.OracleQuery1.SQL.Text := ('select ta.name from cash_games cg join tables ta on cg.table_id=ta.id where cg.id=' + CashGameID);
  FrmMain.OracleQuery1.Execute;
  while not FrmMain.OracleQuery1.eof do
  begin
    com_Table.Items.Add(FrmMain.OracleQuery1.Field('NAME'));
    FrmMain.OracleQuery1.next;
  end;
  com_Table.Text := '';

  // seats
  begin
    com_Seat.Items.Clear;
    FrmMain.OracleQuery1.SQL.Clear;
    FrmMain.OracleQuery1.SQL.Text := ('select SEATS  from cash_games cg left join tables ta on ta.id=cg.table_id where cg.id=' + CashGameID);
    FrmMain.OracleQuery1.Execute;
    if not FrmMain.OracleQuery1.eof then
    begin
      Seats := FrmMain.OracleQuery1.Field('SEATS');
      for I := 1 to Seats do
      begin
        com_Seat.Items.Add(inttostr(I));
      end;
      // GET populated seats
      FrmMain.OracleQuery1.SQL.Clear;
      FrmMain.OracleQuery1.SQL.Text := ('select distinct(SEAT_NUM), SEATS  from cash_games cg left join tables ta on ta.id=cg.table_id left join CASH_GAME_TICKETS cgt on cgt.table_id=cg.table_id  ' +
          'where (cgt.OUT_DATETIME is null)  AND (cgt.DELETED=''0'' or cgt.DELETED is null) AND cg.id=' + CashGameID);
      FrmMain.OracleQuery1.Execute;
      while not FrmMain.OracleQuery1.eof do
      begin
        SeatNum := FrmMain.OracleQuery1.Field('SEAT_NUM');
        SeatIndex := com_Seat.Items.IndexOf(inttostr(SeatNum));
        if SeatIndex > -1 then
        begin
          com_Seat.Items.Delete(SeatIndex);
        end;
        FrmMain.OracleQuery1.next;
      end;
      com_Seat.Text := '';
    end;
  end;
end;

function Tfrm_SellTicket.PopulatePlayerCombo(Name, Surname: string; Sender: TObject): boolean;
var
  Query: string;
begin
  if Sender = uEditPlayers.edt_Name then
    isNameFocused := true
  else
    isNameFocused := false;
  Query := 'select id,(name ||'' ''|| surname) as name from players where UPPER(name) like UPPER(' + '''' + Name + '%' + '''' + ') and UPPER(surname) like UPPER(' + '''' + Surname + '%' + '''' + ')';
  OracleDataSet1.close;
  OracleDataSet1.Session := FrmMain.OracleSession1;
  OracleDataSet1.SQL.Clear;
  OracleDataSet1.SQL.Text := (Query);
  // ---.
  OracleDataSet1.ExecSQL;
  OracleDataSet1.open;
  com_Player.Visible := not OracleDataSet1.eof;
  result := not OracleDataSet1.eof;
  DataSource1.DataSet := OracleDataSet1;
  com_Player.ListSource := DataSource1;
  com_Player.KeyField := 'id';
  com_Player.ListField := 'name';
end;

procedure Tfrm_SellTicket.PopulateSeatCombo(TournamentID: string);
var
  I, SeatNum, Seats, SeatIndex: integer;
begin
  com_Seat.Items.Clear;
  FrmMain.OracleQuery1.SQL.Clear;
  FrmMain.OracleQuery1.SQL.Text := ('select t.id, t.name, t.SEATS, SEAT_NUM from TOURNAMENT_TABLES tt join tables t on tt.TABLE_ID = t.ID ' +
      ' left join (select * from tickets where TOURNAMENT_ID=' + TournamentID + ' and deleted=0) ti on ti.TABLE_ID=t.ID' + ' where tt.TOURNAMENT_ID = ' + TournamentID + ' and T.NAME=''' +
      com_Table.Text + ''' order by seat_num asc');
  FrmMain.OracleQuery1.Execute;
  if FrmMain.OracleQuery1.RowCount > 0 then
  begin
    Seats := FrmMain.OracleQuery1.Field('SEATS');
    for I := 1 to Seats do
    begin
      com_Seat.Items.Add(inttostr(I));
    end;
    while not FrmMain.OracleQuery1.eof do
    begin
      SeatNum := FrmMain.OracleQuery1.Field('SEAT_NUM');
      SeatIndex := com_Seat.Items.IndexOf(inttostr(SeatNum));
      if SeatIndex > -1 then
      begin
        com_Seat.Items.Delete(SeatIndex);
      end;
      FrmMain.OracleQuery1.next;
    end;
    com_Seat.ItemIndex := 0;
  end;
end;

procedure Tfrm_SellTicket.PopulateTableCombo(TournamentID: string);
begin
  m_TournamentID := TournamentID;
  com_Table.Items.Clear;
  FrmMain.OracleQuery1.SQL.Clear;
  FrmMain.OracleQuery1.SQL.Text := ('select (t.seats-count(ti.id)) as seats_free, t.name, t.id  from TOURNAMENT_TABLES tt' + ' left join tables t on tt.TABLE_ID = t.ID' +
      ' left join (select * from tickets where TOURNAMENT_ID=' + TournamentID + ' and deleted=0) ti on ti.TABLE_ID=t.ID' + ' where tt.TOURNAMENT_ID = ' + TournamentID +
      ' group by t.name, t.id, t.seats');
  FrmMain.OracleQuery1.Execute;
  while not FrmMain.OracleQuery1.eof do
  begin
    if FrmMain.OracleQuery1.Field('SEATS_FREE') > 0 then
    begin
      com_Table.Items.Add(FrmMain.OracleQuery1.Field('NAME'))
    end;
    FrmMain.OracleQuery1.next;
  end;
end;

procedure Tfrm_SellTicket.GetCashGameData(CashGameID, DoRebuyID: string);
begin
  if DoRebuyID <> '' then
  begin
    m_TicketType := TicketTypeRebuy;
    pnl_TicketType.Caption := _('REBUY') + ' ' + _('TICKET');
    pnl_CalcTicket.Visible := true;
    edt_Fee.Text := '0';
  end
  else
  begin
    m_TicketType := TicketTypeBuy;
    pnl_TicketType.Caption := _('BUY') + ' ' + _('TICKET');
    pnl_CalcTicket.Visible := true;
    edt_Fee.Text := '0';
  end;
  FrmMain.OracleQuery1.SQL.Clear;
  FrmMain.OracleQuery1.SQL.Text := ('SELECT NAME,TABLE_ID,MIN_IN FROM CASH_GAMES where id=' + frmCageCashGame.stg_CashGames.Cells[0, frmCageCashGame.stg_CashGames.Row]);
  FrmMain.OracleQuery1.Execute;
  if not FrmMain.OracleQuery1.eof then
  begin
    lbl_TournamentName.Caption := _('Cash Game:') + ' ' + FrmMain.OracleQuery1.Field('NAME');
    m_MinBuyIn := StrToFloat(FrmMain.OracleQuery1.Field('MIN_IN'));
  end;
end;

procedure Tfrm_SellTicket.GetTableAndSeat(TournamentID, CashGameID, TicketId, PlayerID: string);
begin
  if ((TicketId <> '') and (TicketId <> '-1')) or ((PlayerID <> '') and (PlayerID <> '-1')) then
  begin
    FrmMain.OracleQuery1.SQL.Clear;
    if CashGameID = '' then
    begin
      PopulateTableCombo(TournamentID);
      PopulateSeatCombo(TournamentID);
      FrmMain.OracleQuery1.SQL.Text := ('SELECT (SELECT NAME FROM TABLES WHERE ID=TABLE_ID) AS NAME, SEAT_NUM FROM TICKETS where id=' + TicketId)
    end
    else
    begin
      PopulateCashGameTableAndSeat(CashGameID);
      com_Table.Enabled := false;
      com_Seat.Enabled := false;
      FrmMain.OracleQuery1.SQL.Text := ('SELECT (SELECT NAME FROM TABLES WHERE ID=TABLE_ID) AS NAME, SEAT_NUM FROM CASH_GAME_TICKETS  where player_id=' + PlayerID);
    end;
    FrmMain.OracleQuery1.Execute;
    if not FrmMain.OracleQuery1.eof then
    begin
      com_Table.Text := VarToStr(FrmMain.OracleQuery1.Field('NAME'));
      com_Seat.Text := VarToStr(FrmMain.OracleQuery1.Field('SEAT_NUM'));
    end;
  end;
end;

function Tfrm_SellTicket.GetTournamentData(TournamentID: string): boolean;
var
  Fee: string;
begin
  result := false;
  // CHECK IF TURNIR IS FINISHED
  if frmCageTournament.stg_Tournaments.Cells[13, frmCageTournament.stg_Tournaments.Row] = 'FINISHED' then
  begin
    ShowMessage(_('Tournament already finished!'));
    exit;
  end;
  // ----------------------
  FrmMain.OracleQuery1.SQL.Clear;
  FrmMain.OracleQuery1.SQL.Text := ('SELECT * FROM TOURNAMENTS T LEFT JOIN ( SELECT TOURNAMENT_ID, SEQ_INDEX FROM GETPRESENTTOURNAMENTROUNDDATA' +
      ') TT ON TT.TOURNAMENT_ID=T.ID LEFT JOIN TOURNAMENT_ROUNDS TR ON TR.SEQ_INDEX=TT.SEQ_INDEX AND TR.TOURNAMENT_ID=T.ID WHERE T.ID=' + TournamentID);
  FrmMain.OracleQuery1.Execute;
  Fee := FrmMain.OracleQuery1.Field('FEE');
  com_FeeType.ItemIndex := FrmMain.OracleQuery1.Field('FEE_IS_PERCENT');
  m_RebuyAllowed := false;
  if StrToB(FrmMain.OracleQuery1.Field('REBUY_ALLOWED')) then
  begin
    if FrmMain.OracleQuery1.Field('REBUY_OR_ADDON') = 'REBUY' then
    begin
      m_RebuyAllowed := true;
    end;
    if FrmMain.OracleQuery1.Field('REBUY_OR_ADDON') = 'ADDON' then
    begin
      m_AddonAllowed := true;
    end;
  end;
  // CHECK TICKETS COUNT
  if m_TicketType = TicketTypeBuy then
  begin
    FrmMain.OracleQuery1.SQL.Clear;
    FrmMain.OracleQuery1.SQL.Text := ('SELECT COUNT(0) AS PLAYERS,SEATS FROM TICKETS TI' + ' JOIN (SELECT SUM(SEATS) AS SEATS, TOURNAMENT_ID FROM TOURNAMENT_TABLES TT' +
        ' JOIN TABLES TA ON TA.ID=TT.TABLE_ID WHERE TOURNAMENT_ID=' + TournamentID + '' + ' GROUP BY TOURNAMENT_ID)X ON TI.TOURNAMENT_ID=TI.TOURNAMENT_ID' + ' WHERE DELETED=0 AND TI.TOURNAMENT_ID=' +
        TournamentID + ' GROUP BY SEATS');
    FrmMain.OracleQuery1.Execute;
    if not FrmMain.OracleQuery1.eof then
    begin
      if (FrmMain.OracleQuery1.Field('SEATS') <= FrmMain.OracleQuery1.Field('PLAYERS')) then
      begin
        ShowMessage(_('Seats for tournament is full!'));
        exit;
      end;
    end;
  end;
  m_LateRegMinutes := FrmMain.OracleQuery1.Field('LATE_REGISTRATION_MIN');
  m_EventStart := FrmMain.OracleQuery1.Field('EVENT_START');
  m_MinBuyIn := FrmMain.OracleQuery1.Field('BUY_IN');
  m_BuyIn := FrmMain.OracleQuery1.Field('BUY_IN');
  lbl_TournamentName.Caption := _('Tournament:') + ' ' + FrmMain.OracleQuery1.Field('NAME');
  btn_RandomPosition.Enabled := true;
  m_Fee := Fee;
  if Fee <> '' then
  begin
    edt_Fee.Visible := true;
    com_FeeType.Visible := true;
  end
  else
  begin
    edt_Fee.Visible := false;
    com_FeeType.Visible := false;
  end;
  PopulateTableCombo(TournamentID);
  result := true;
end;

procedure Tfrm_SellTicket.ShowSellTicketForm(BuyValue, TournamentID, PlayerID, TicketId: string; CashGameID: string; DoRebuyID: string; DoAddonID: string);
begin
  // Check if tournament seats is full
  if TournamentID <> '' then
  begin
    if (PlayerID = '') and (frmCageTournament.stg_Tournaments.Cells[18, frmCageTournament.stg_Tournaments.Row] = '0') then // FREE_POS
    begin
      ShowMessage(_('Free seats not available!'));
      exit;
    end;
  end;
  pnl_TicketType.Caption := '';
  m_TicketID := TicketId;
  m_CashGameID := CashGameID;
  m_DoRebuyId := DoRebuyID;
  m_DoAddonId := DoAddonID;
  com_Table.Enabled := true;
  com_Seat.Enabled := true;
  edt_BuyIn.Text := '';
  edt_Fee.Text := '';
  if CheckAddonRebuyFinished((CashGameID <> ''), m_DoRebuyId, m_DoAddonId) then
  begin
    frmCageTournament.dtp_DateChange(self);
    exit;
  end;
  btn_ClearEdit.Click;
  edt_BuyIn.Text := BuyValue;
  if (CashGameID <> '') and (TournamentID = '') then
  begin
    m_isCashGame := true;
    GetCashGameData(CashGameID, DoRebuyID);
    PopulateCashGameTableAndSeat(CashGameID);
  end
  else
  begin
    m_isCashGame := false;
    if TournamentID <> '' then
    begin
      if not GetTournamentData(TournamentID) then
        exit;
    end;
  end;
  if PlayerID <> '' then
  begin
    com_Player.KeyValue := PlayerID;
    com_Player2Click(self);
  end;
  GetTableAndSeat(TournamentID, CashGameID, TicketId, PlayerID);
  if not showing then
    ShowModal;
end;

end.
